package com.youpai.platform.vulture.service.handler.flag;

import com.youpai.platform.chat.service.service.ChatMessageFacadeInterface;
import com.youpai.platform.common.exceptions.RemoteException;
import com.youpai.platform.vulture.common.entity.AccessMessage;
import com.youpai.platform.vulture.common.entity.Header;
import com.youpai.platform.vulture.common.enums.ClientCommandEnum;
import com.youpai.platform.vulture.common.enums.HeaderTypeEnum;
import com.youpai.platform.vulture.service.channel.ChannelAttrs;
import com.youpai.platform.vulture.service.channel.VultureChannel;
import com.youpai.platform.vulture.service.entity.dto.ReceiveMessageDTO;
import com.youpai.platform.vulture.service.handler.vulture.MessageHandler;
import io.netty.channel.ChannelHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @date: 2022/7/10 17:42
 * @author: Anna
 * @version: 1.0
 * @description: 普通消息处理
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class OrdinaryMessageHandler implements MessageHandler {

    @Resource
    private ChatMessageFacadeInterface chatMessageFacadeInterface;

    @Override
    public void handle(VultureChannel vultureChannel, AccessMessage accessMessage) throws RemoteException {
        List<Header> headerList = accessMessage.getHeaderList();
        if (CollectionUtils.isEmpty(headerList)) {
            throw new RemoteException(vultureChannel, "header为空");
        }
        for (Header header : headerList) {
            // 是否是C2C消息
            if (isC2CMessage(header)) {
                handC2CMessage(vultureChannel, accessMessage.getBody());
            }
        }
    }

    private boolean isC2CMessage(Header header) {
        return header.getHeaderType() == HeaderTypeEnum.COMMAND.type
                && ClientCommandEnum.CLI_SEND_MSG.cmd == (int) header.getHeaderValue();
    }

    private void handC2CMessage(VultureChannel vultureChannel, String body) throws RemoteException {
        ChannelAttrs attrs = ChannelAttrs.getAttrs(vultureChannel);
        ReceiveMessageDTO receiveMessageDTO = new ReceiveMessageDTO();
        receiveMessageDTO.setBody(body)
                .setAppId(attrs.getAppId())
                .setFromAccId(attrs.getAccId());
        chatMessageFacadeInterface.receive(receiveMessageDTO);
    }
}
